package e.odbo.data.model.comparable;

import e.odbo.data.OdbO;
import e.odbo.data.util.ArrayUtils;

import java.util.regex.Pattern;

public abstract class VersionComparable implements Comparable<String>{
        /*
      要求，必须是三位，x.x.x的形式，
      每位x的范围分别为1-99,0-99,0-99。
      不允许的情况0.x.x；01.x.x; x.0x.x; x.00.x； x.x.00; x.x.0x
     */
    public static VersionComparable VER_3_2_1(String currentVer){
        return new VersionComparable(currentVer, OdbO.PATTERN.VER_3_2_1_Pattern) {

            @Override
            String[] splitVersionString(String verString) {
                return verString.split("\\.");
            }
        };
    }

    //2018-02-01
    public static VersionComparable VER_2018_08_01(String currentVer){
        return new VersionComparable(currentVer, OdbO.PATTERN.VER_2018_08_01_Pattern) {

            @Override
            String[] splitVersionString(String verString) {
                return verString.split("-");
            }
        };
    }

    public static VersionComparable AUTO(String currentVer){
        VersionComparable ret=null;
        if( OdbO.PATTERN.VER_3_2_1_Pattern.matcher(currentVer).matches())
            ret= VER_3_2_1(currentVer);
        else if( OdbO.PATTERN.VER_2018_08_01_Pattern.matcher(currentVer).matches())
           ret=VER_2018_08_01(currentVer);
        return ret;
    }


    String currentVersion;
    Pattern pattern;

    public  VersionComparable(String currentVer, Pattern pattern) {
        this.currentVersion = currentVer;
        this.pattern=pattern;
    }

    public VersionComparable(String currentVer, String patternStr) {
        this.currentVersion = currentVer;
        this.pattern=Pattern.compile(patternStr);
    }

    public boolean match(String checkVer){
        return pattern.matcher(checkVer).matches();
    }

    public String getCurrentVersion() {
        return currentVersion;
    }

    abstract String[] splitVersionString(String verString);

    @Override
    public int compareTo(String o) {
        if(null==o||o.isEmpty())
            return 1;
        if(!currentVersion.equalsIgnoreCase(o)){
            String[] curVer=splitVersionString(currentVersion);
            String[] oldVer=splitVersionString(o);
            return ArrayUtils.compareUseInteger(curVer,oldVer);
        }
        return 0;
    }
}
